package com.swift.violent.mainstay.config.expand;

import cn.hutool.core.map.MapUtil;
import com.github.alenfive.rocketapi.entity.ApiInfo;
import com.github.alenfive.rocketapi.entity.ApiParams;
import com.github.alenfive.rocketapi.extend.IApiPager;
import com.github.alenfive.rocketapi.function.UtilsFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * 分页构造器
 *
 * @author xuhaifeng
 * @date 2021.1.19 21:39
 */
@Component
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
public class DefaultApiPager implements IApiPager {
    @Autowired
    private UtilsFunction utilsFunction;

    @Override
    public Object buildPager(Long totalRecords, List data, ApiInfo apiInfo, ApiParams apiParams) {
        final Integer index = Integer.valueOf(String.valueOf(utilsFunction.val(this.getIndexVarName())));
        final Integer pageNo = Integer.valueOf(String.valueOf(utilsFunction.val(this.getPageNoVarName())));
        final Integer pageSize = Integer.valueOf(String.valueOf(utilsFunction.val(this.getPageSizeVarName())));
        return MapUtil.builder(new HashMap<String, Object>(10))
                .put("data", data)
                .put(this.getIndexVarName(), index)
                .put("totalRecords", totalRecords)
                .put(this.getPageSizeVarName(), pageNo)
                .put(this.getPageNoVarName(), pageSize)
                .put("totalPages", (int) (totalRecords + pageSize - 1) / pageSize)
                .build();
    }

    @Override
    public String getPageSizeVarName() {
        return "pageSize";
    }

    @Override
    public String getPageNoVarName() {
        return "pageNo";
    }

    @Override
    public String getIndexVarName() {
        return "index";
    }

    @Override
    public Integer getIndexVarValue(Integer pageSize, Integer pageNo) {
        return (pageNo - 1) * pageSize;
    }

    @Override
    public Integer getPageSizeDefaultValue() {
        return 10;
    }

    @Override
    public Integer getPageNoDefaultValue() {
        return 1;
    }
}